# -*- coding: utf-8 -*-
from hashlib import md5
from uuid import uuid4

from common.mch.model import *
from common.utils import exceptions as err
from common.utils import track_logging
from common.utils.decorator import sql_wrapper

_LOGGER = track_logging.getLogger(__name__)

_SALT = u"V!$#s*PY"


def encode_password(passwd):
    return md5(passwd.encode('utf-8') + _SALT).hexdigest()


@sql_wrapper
def get_account(mch_id):
    return MchAccount.query.filter(MchAccount.id == mch_id).first()


@sql_wrapper
def create_account(name, pwd):
    account = MchAccount()
    account.name = name
    account.password = encode_password(pwd)
    account.api_key = uuid4().hex
    account.save()
    return account


@sql_wrapper
def get_mch_dct():
    mchs = MchAccount.query.all()
    mch_dct = {}
    for mch in mchs:
        mch_dct[mch.id] = mch.name
    return mch_dct


@sql_wrapper
def get_mch_info(mch_id):
    mch_info = MchAccount.query.filter(MchAccount.id == mch_id).first()
    if not mch_info:
        raise err.ParamError('mch id not exists')
    return mch_info.as_dict()


@sql_wrapper
def get_mch_info_by_name(name):
    mch_info = MchAccount.query.filter(MchAccount.name == name).first()
    if not mch_info:
        raise err.ParamError('mch id not exists')
    return mch_info.as_dict()
